<template>
	<view class="container">
		<view class="form-container">
			<view class="form-item">
				<text class="form-label">收货人</text>
				<input class="form-input" v-model="addressForm.receiverName" placeholder="请输入收货人姓名" />
			</view>
			
			<view class="form-item">
				<text class="form-label">手机号码</text>
				<input class="form-input" v-model="addressForm.receiverPhone" placeholder="请输入手机号码" type="number" maxlength="11" />
			</view>
			
			<view class="form-item">
				<text class="form-label">详细地址</text>
				<textarea class="form-textarea" v-model="addressForm.detailedAddress" placeholder="请输入详细地址" />
			</view>
			
			<view class="form-item switch-item">
				<text class="form-label">设为默认地址</text>
				<switch :checked="addressForm.isDefault" @change="onSwitchChange" color="#409EFF" />
			</view>
		</view>
		
		<view class="btn-container">
			<button class="save-btn" @click="saveAddress">保存</button>
		</view>
	</view>
</template>

<script>
import http from '@/utils/request';

export default {
	data() {
		return {
			addressForm: {
				id: null,
				userId: null,
				receiverName: '',
				receiverPhone: '',
				detailedAddress: '',
				isDefault: false
			},
			isEdit: false
		};
	},
	onLoad(options) {
		this.checkLoginStatus();
		
		// 判断是编辑还是新增
		if (options.type === 'edit' && options.id) {
			this.isEdit = true;
			this.addressForm.id = options.id;
			this.getAddressDetail(options.id);
		} else {
			this.isEdit = false;
		}
	},
	methods: {
		// 检查登录状态
		checkLoginStatus() {
			const userStr = uni.getStorageSync('user');
			if (userStr) {
				try {
					const userInfo = JSON.parse(userStr);
					if (userInfo && userInfo.id) {
						this.addressForm.userId = userInfo.id;
						return true;
					}
				} catch (error) {
					console.error('解析用户信息失败', error);
				}
			}
			
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			});
			
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/login/login'
				});
			}, 1500);
			
			return false;
		},
		
		// 获取地址详情
		async getAddressDetail(id) {
			try {
				const response = await http.get(`/address/detail/${id}`);
				if (response.code === 200) {
					const { receiverName, receiverPhone, detailedAddress, isDefault, userId } = response.data;
					this.addressForm = {
						id,
						userId,
						receiverName,
						receiverPhone,
						detailedAddress,
						isDefault: isDefault === true || isDefault === 1
					};
				} else {
					uni.showToast({
						title: response.message || '获取地址详情失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取地址详情失败:', error);
				uni.showToast({
					title: '获取地址详情失败',
					icon: 'none'
				});
			}
		},
		
		// 切换默认地址开关
		onSwitchChange(e) {
			this.addressForm.isDefault = e.detail.value;
		},
		
		// 表单验证
		validateForm() {
			if (!this.addressForm.receiverName) {
				uni.showToast({
					title: '请输入收货人姓名',
					icon: 'none'
				});
				return false;
			}
			
			if (!this.addressForm.receiverPhone) {
				uni.showToast({
					title: '请输入手机号码',
					icon: 'none'
				});
				return false;
			}
			
			// 验证手机号
			const phoneReg = /^1[3-9]\d{9}$/;
			if (!phoneReg.test(this.addressForm.receiverPhone)) {
				uni.showToast({
					title: '请输入正确的手机号码',
					icon: 'none'
				});
				return false;
			}
			
			if (!this.addressForm.detailedAddress) {
				uni.showToast({
					title: '请输入详细地址',
					icon: 'none'
				});
				return false;
			}
			
			if (this.addressForm.detailedAddress.length < 5) {
				uni.showToast({
					title: '详细地址至少5个字符',
					icon: 'none'
				});
				return false;
			}
			
			return true;
		},
		
		// 保存地址
		async saveAddress() {
			if (!this.checkLoginStatus()) return;
			
			// 表单验证
			if (!this.validateForm()) return;
			
			try {
				let response;
				if (this.isEdit) {
					response = await http.put('/address/update', this.addressForm);
				} else {
					response = await http.post('/address/add', this.addressForm);
				}
				
				if (response.code === 200) {
					uni.showToast({
						title: this.isEdit ? '更新地址成功' : '添加地址成功',
						icon: 'success'
					});
					
					// 返回上一页
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} else {
					uni.showToast({
						title: response.message || (this.isEdit ? '更新地址失败' : '添加地址失败'),
						icon: 'none'
					});
				}
			} catch (error) {
				console.error(this.isEdit ? '更新地址失败:' : '添加地址失败:', error);
				uni.showToast({
					title: this.isEdit ? '更新地址失败' : '添加地址失败',
					icon: 'none'
				});
			}
		}
	}
};
</script>

<style>
.container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding: 30rpx;
}

.form-container {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 20rpx 30rpx;
}

.form-item {
	padding: 30rpx 0;
	border-bottom: 1rpx solid #eee;
}

.form-item:last-child {
	border-bottom: none;
}

.form-label {
	display: block;
	font-size: 28rpx;
	color: #333;
	margin-bottom: 20rpx;
	font-weight: bold;
}

.form-input {
	width: 100%;
	height: 80rpx;
	font-size: 28rpx;
	color: #333;
	padding: 0 20rpx;
	box-sizing: border-box;
	border: 1rpx solid #ddd;
	border-radius: 8rpx;
}

.form-textarea {
	width: 100%;
	height: 180rpx;
	font-size: 28rpx;
	color: #333;
	padding: 20rpx;
	box-sizing: border-box;
	border: 1rpx solid #ddd;
	border-radius: 8rpx;
}

.switch-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.switch-item .form-label {
	margin-bottom: 0;
}

.btn-container {
	margin-top: 50rpx;
}

.save-btn {
	background-color: #409EFF;
	color: #fff;
	border-radius: 44rpx;
	font-size: 32rpx;
	height: 88rpx;
	line-height: 88rpx;
}
</style> 